import path from 'node:path';
import os from 'node:os';
import fs from 'node:fs';
import { CursorPaths } from '../../src/types';

function getWindowsPaths(): Partial<CursorPaths> {
    const appdata = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
    const localappdata = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');

    if (!appdata || !localappdata) {
        return {};
    }

    const paths = {
        storage_path: path.join(appdata, "Cursor", "User", "globalStorage", "storage.json"),
        sqlite_path: path.join(appdata, "Cursor", "User", "globalStorage", "state.vscdb"),
        machine_id_path: path.join(appdata, "Cursor", "machineId"),
        cursor_path: path.join(localappdata, "Programs", "Cursor"),
        updater_path: path.join(localappdata, "cursor-updater"),
        update_yml_path: path.join(localappdata, "Programs", "Cursor", "resources", "app-update.yml"),
        product_json_path: path.join(localappdata, "Programs", "Cursor", "resources", "app", "product.json"),
    };

    try {
        // 确保基础目录存在，以避免后续操作因目录不存在而失败
        fs.mkdirSync(path.dirname(paths.storage_path), { recursive: true });
    } catch (e) {
        console.error("Failed to create directory for Cursor paths:", e);
    }


    return paths;
}

function getMacPaths(): Partial<CursorPaths> {
    const home = os.homedir();
    const appSupport = path.join(home, 'Library/Application Support');

    const paths = {
        storage_path: path.join(appSupport, "Cursor/User/globalStorage/storage.json"),
        sqlite_path: path.join(appSupport, "Cursor/User/globalStorage/state.vscdb"),
        machine_id_path: path.join(appSupport, "Cursor/machineId"),
        cursor_path: "/Applications/Cursor.app",
        updater_path: path.join(appSupport, "cursor-updater"),
        update_yml_path: "/Applications/Cursor.app/Contents/Resources/app-update.yml",
        product_json_path: "/Applications/Cursor.app/Contents/Resources/app/product.json",
    };
    
    try {
        // 确保基础目录存在
        fs.mkdirSync(path.dirname(paths.storage_path), { recursive: true });
    } catch(e) {
        console.error("Failed to create directory for Cursor paths:", e);
    }


    return paths;
}

/**
 * Detects and returns the standard paths for the Cursor application 
 * based on the operating system.
 * This implementation is based on standard installation locations and does not
 * rely on runtime discovery, making it more robust.
 */
export function detectCursorPath(): Partial<CursorPaths> {
    try {
        switch (process.platform) {
            case 'win32':
                return getWindowsPaths();
            case 'darwin':
                return getMacPaths();
            default:
                // Potentially add Linux paths here if needed
                return {};
        }
    } catch (error) {
        console.error("Error detecting Cursor paths:", error);
        return {};
    }
} 